import { createSlice } from '@reduxjs/toolkit'
import { getToken, setToken as _setToken, clearToken } from '@/utils/token'
import { loginAPI,getProfileAPI} from 'src/apis/user' 
const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      // 存入本地
      _setToken(state.token)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    ClearUserInfo(state, action) {
      state.userInfo = {}
      state.token = ''
      clearToken()
    }
  }
})

// 解构出actionCreater
const { setToken, setUserInfo,ClearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}

//获取个人用户信息
const fetchUserInfo = (loginForm) => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { fetchLogin, fetchUserInfo, setToken,ClearUserInfo }

export default userReducer